
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');


var ztRouter = require('./routes/zt');
var cwsRouter = require('./routes/cws');
var ylRouter = require('./routes/yl');
var cxfRouter = require('./routes/cxf');
var cywRouter = require('./routes/cyw');
// app.js

const http = require("http");
const WebSocket = require("ws");
const logger = require("morgan");
const createError = require("http-errors");
const { User } = require("./model/model"); // 确保路径正确
const nodemailer = require('nodemailer');




let cors = require('cors')
var app = express();
app.use(cors({
  origin: 'http://localhost:5173',
  methods: ['GET', 'POST', 'PUT', 'DELETE'],
  allowedHeaders: ['Content-Type', 'Authorization']
}))
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "public")));

// CORS配置（必须放在路由前面）
app.use(cors({
  origin: "http://localhost:5173",
  methods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
  allowedHeaders: ["Content-Type", "Authorization"],
  credentials: true
}));

// 创建HTTP服务器
const server = http.createServer(app);

// WebSocket配置
const wss = new WebSocket.Server({ server });
const onlineUsers = new Map();

// WebSocket连接处理
// WebSocket连接事件处理
wss.on("connection", (ws, req) => {
  const url = new URL(req.url, `http://${req.headers.host}`);
  // 从URL查询参数获取用户ID
  const userId = url.searchParams.get("userId");

  // 用户验证
  // 数据库查询用户信息
  User.findById(userId).then(user => {
    if (!user) {
      ws.close(1008, "用户不存在");
      return;
    }

    // 添加用户到在线列表
    // 将用户加入在线列表
    onlineUsers.set(userId, ws);
    broadcastOnlineUsers();

    // 消息处理
    // 消息接收事件处理
    ws.on("message", async data => {
      try {
        const message = JSON.parse(data);
        const { to, content } = message;

        const targetUser = await User.findById(to);
        if (!targetUser) return;

        // 在线消息处理
        if (onlineUsers.has(to)) {
          onlineUsers.get(to).send(JSON.stringify({
            type: "message",
            from: userId,
            content: content
          }));
        }
        // 离线邮件处理
        else {
          // 创建邮件传输器（需配置SMTP服务）
          const transporter = nodemailer.createTransport({
            host: "smtp.qq.com",
            port: 465,
            secure: true,
            auth: {
              user: process.env.EMAIL_USER || "3487490065@qq.com",
              pass: process.env.EMAIL_PASS || "jowlmcmvcvxdcjib"
            },
            tls: { rejectUnauthorized: false }
          });

          await transporter.sendMail({
            from: `"聊天系统" <${process.env.EMAIL_USER || "3487490065@qq.com"}>`,
            to: targetUser.email,
            subject: `新消息来自 ${user.username}`,
            html: `
              <p>发送者ID: ${userId}</p>
              <p>内容: ${content}</p>
              <p>时间: ${new Date().toLocaleString()}</p>
            `
          });
        }
      } catch (error) {
        console.error("消息处理错误:", error);
      }
    });

    // 断开连接处理
    ws.on("close", () => {
      onlineUsers.delete(userId);
      User.findByIdAndUpdate(userId, { online: false }).exec();
      broadcastOnlineUsers();
    });

  }).catch(error => {
    console.error("数据库错误:", error);
    ws.close(1008, "服务器错误");
  });
});

// 广播在线用户列表
function broadcastOnlineUsers() {
  const users = Array.from(onlineUsers.keys());
  wss.clients.forEach(client => {
    if (client.readyState === WebSocket.OPEN) {
      client.send(JSON.stringify({
        type: "online-users",
        users: users
      }));
    }
  });
}

// 路由配置
app.use('/zt', ztRouter);
app.use('/cws', cwsRouter);
app.use('/yl', ylRouter);
app.use('/cxf', cxfRouter);
app.use('/cyw', cywRouter);
app.use('/upload', express.static(path.join(__dirname, 'upload')));
// 错误处理
app.use((req, res, next) => next(createError(404)));
app.use((err, req, res, next) => {
  if (res.headersSent) {
    return;
  }
  res.status(err.status || 500);
  res.json({
    error: {
      status: err.status || 500,
      message: err.message
    }
  });
});

// 启动服务器
server.listen(3001, () => {
  console.log("HTTP服务器运行在 http://localhost:3001");
  console.log("WebSocket服务器运行在 ws://localhost:3001");
});

module.exports = app;